package com.stn.zjx.givingtreasure.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.task.XExecutor;
import com.stn.zjx.givingtreasure.MainActivity;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.broadcastreceiver.NotificationBroadcastReceiver;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.UUID;

public class AppUpdateService extends Service implements XExecutor.OnAllTaskEndListener {

    private static final int PUSH_NOTIFICATION_ID =10;
    private static final String PUSH_CHANNEL_ID = "down";
    private static final String PUSH_CHANNEL_NAME = "ss";



     public String tag="update_version_app";
    private OkDownload okDownload;
    public String download_url="";
    public Context context;
    public NotificationManager nm;
    public  NotificationCompat.Builder builder;
    @Override
    public void onCreate() {
        super.onCreate();
        this.context=getApplicationContext();
          nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(PUSH_CHANNEL_ID, PUSH_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableVibration(false);
            channel.setVibrationPattern(new long[]{0});
            channel.setSound(null,null);
            if (nm != null) {
                nm.createNotificationChannel(channel);
            }

        }
        builder = new NotificationCompat.Builder(context,PUSH_CHANNEL_ID);
        builder.setDefaults(NotificationCompat.DEFAULT_LIGHTS);
        builder.setVibrate(null);
        builder.setVibrate(new long[]{0l});
        builder.setSound(null);
        builder.setLights(0, 0, 0);


        okDownload=OkDownload.getInstance();
        String path= Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.app_name)+"/download";
        File file=new File(path);
         if(!file.getParentFile().exists()){
             file.getParentFile().mkdirs();
         }
         if(!file.exists()){
             file.mkdirs();
         }
        okDownload.setFolder(path);
        okDownload.getThreadPool().setCorePoolSize(1);
        okDownload.addOnAllTaskEndListener(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        download_url=intent.getStringExtra("download_url");
        if(download_url!=null){
            startDownload(download_url);
        }
        Log.d("*******************","启动下载服务"+download_url);
        return super.onStartCommand(intent, flags, startId);
    }

    public void startDownload(String url){
        GetRequest<File> request=OkGo.<File>get(download_url);
        JSONObject apk=new JSONObject();
        try {
            apk.put("download_url",url);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        DownloadTask task=OkDownload.request(tag,request)
                .priority(99)
                .fileName("com.stn.zjx.givingtreasure"+ UUID.randomUUID().toString().substring(0,4)+".apk")
                .extra1(apk.toString())
                .save()
                .register(new ApkDownloadListener(tag));
         task.start();

    }

    @Override
    public void onAllTaskEnd() {
           okDownload.removeTask(tag);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
             okDownload.removeOnAllTaskEndListener(this);
     }

        public class ApkDownloadListener extends DownloadListener{

            public ApkDownloadListener(Object tag) {
                super(tag);
            }
            @Override
            public void onStart(Progress progress) {
                builder.setContentTitle("正在下载中....");
                builder.setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        .setAutoCancel(false)
                        .setContentText("下载进度："+"0%")
                        .setTicker("下载进度："+"0%")
                        .setWhen(SystemClock.currentThreadTimeMillis())
                        .setChannelId(PUSH_CHANNEL_ID)
                        .setProgress(100,0,false);
                Notification notification=builder.build();


                notification.flags|=Notification.FLAG_AUTO_CANCEL;
              if(nm!=null){
                  nm.notify(PUSH_NOTIFICATION_ID, notification);
              }

                Log.d("*******************","开始下载");
            }

            @Override
            public void onProgress(Progress progress) {
                Log.d("*******************","progress:"+progress);
                builder.setContentTitle("正在下载中....");
                builder.setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        .setTicker("下载进度:" + (int) (progress.fraction * 100) + "%")
                        .setChannelId(PUSH_CHANNEL_ID)
                        .setAutoCancel(false);
                builder.setProgress(100, (int) (progress.fraction * 100), false);
                builder.setContentText("下载进度:" + (int) (progress.fraction * 100) + "%");
                Notification notification=builder.build();
                notification.flags|=Notification.FLAG_AUTO_CANCEL;

                if(nm!=null){
                    nm.notify(PUSH_NOTIFICATION_ID, notification);
                }
            }

            @Override
            public void onError(Progress progress) {
                builder.setContentTitle("点击重新下载");
                builder.setContentText("下载失败");
                builder.setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        .setTicker("下载失败")
                        .setChannelId(PUSH_CHANNEL_ID)
                        .setAutoCancel(true);
                Intent start=new Intent(getApplicationContext(),NotificationBroadcastReceiver.class);

                start.putExtra("flag",NotificationBroadcastReceiver.FLAG_DOWNLOAD_ERROR);
                 start.putExtra("data",download_url);

                PendingIntent pi = PendingIntent.getBroadcast(context, 0,start, 0);
                builder.setContentIntent(pi);
                Notification notification=builder.build();
                notification.flags|=Notification.FLAG_AUTO_CANCEL;

                if(nm!=null){
                    nm.notify(PUSH_NOTIFICATION_ID, notification);
                }
            }

            @Override
            public void onFinish(File file, Progress progress) {

                builder.setContentTitle("下载完成");
                builder.setContentText("点击安装");
                builder.setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        .setTicker("点击安装")
                        .setWhen(SystemClock.currentThreadTimeMillis())
                        .setChannelId(PUSH_CHANNEL_ID)
                        .setAutoCancel(true);
                builder.setProgress(100, (int) (progress.fraction * 100), false);
                PendingIntent pi = PendingIntent.getActivity(context, 0, getInstallIntent(file), 0);
                builder.setContentIntent(pi);
                Notification notification=builder.build();
                notification.flags|=Notification.FLAG_AUTO_CANCEL;

                if(nm!=null){
                    nm.notify(PUSH_NOTIFICATION_ID, notification);
                }
//                ToolsUtils.install(getApplicationContext(),file);
                Log.d("*******************","下载完成:"+file.getAbsolutePath());
            }

            @Override
            public void onRemove(Progress progress) {

            }
        }

        public Intent getInstallIntent(File file){
            Intent intent = new Intent(Intent.ACTION_VIEW);
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
                Uri apkUri = FileProvider.getUriForFile(context, "com.stn.zjx.givingtreasure.fileprovider", file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
                context.startActivity(install);
            } else{
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
                context.startActivity(install);
            }
            return intent;
        }


}
